package edu.uwosh.cs342.placestobe;

import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class FriendsActivity extends Activity{
	ArrayList<String> friendsFromServer = new ArrayList<String>();
	private ListView friendsListView;
	String userID = MainActivity.userID;
	String newFriend = "";
	String friendToRemove = "NOPE...";
    ArrayList<String> friendsList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		new AsyncGetFriends().execute((Object[]) null);
	
	}
	
	
	private class AsyncGetFriends extends AsyncTask<Object, Object, Object>{
		String response = "";		
		@Override
		protected Object doInBackground(Object... arg0) {	
			try {  
				response = CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/viewFriends.php?userID="+userID); 
				response = response.toString().trim();
			} catch (Exception e) {  System.out.println(e.toString());}
			return null;
		}
		@Override
		protected void onPostExecute(Object result){
			fillFriends(response);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater blowUp = getMenuInflater();
		blowUp.inflate(R.menu.friends_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			case R.id.addFriend:
				getNewFriendName();
			break;
		}
		return false;
	}
	
	private void fillFriends(String friendsStr){
		StringTokenizer tk = new StringTokenizer(friendsStr);
		friendsList = new ArrayList<String>();
		while(tk.hasMoreTokens()){
			friendsList.add(tk.nextToken());
		}
		// fill the friendsFromServer List View
		friendsListView = (ListView)  findViewById(R.id.listViewFriends);
		CustomListAdapter adapter = new CustomListAdapter(this , R.layout.custom_list , friendsList);
		friendsListView.setAdapter(adapter);

		friendsListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent,final View view, final int position, long id) {
				new AlertDialog.Builder(FriendsActivity.this)
			    .setTitle("Delete")
			    .setMessage("Do you want to delete friend?")
			    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int whichButton) {	
			        	try{
			        		friendToRemove = friendsList.get(position).toString();
			        	}catch(Exception e){ System.out.println(e.toString());}
			        	new AsyncDeleteFriend().execute((Object[]) null);
			        }
			    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int whichButton) {
			            // Do nothing.
			        }
			    }).show();
				return false;
		}});
		
	}
	
	private class AsyncAddFriend extends AsyncTask<Object, Object, Object>{
		String res = "";
		@Override
		protected Object doInBackground(Object... params) {			
			String response = null;  
			try {
				response = CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/addFriend.php?userID="+userID+ "&friendID="+newFriend);
				res=response.toString();
				res = res.trim();
			}catch (Exception e) {} 	
			return null;
		}
		@Override
		protected void onPostExecute(Object result){
			if(res.equals("1")){
				Toast.makeText(getApplicationContext(), "Added user "+ newFriend +  " to friendsFromServer list.", Toast.LENGTH_SHORT).show();
				friendsFromServer.add(newFriend);
				startActivity(new Intent("android.intent.action.FRIENDSACTIVITY"));
			}else{
				Toast.makeText(getApplicationContext(), "User does not exist.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	
	/*
	 * AsyncDeleteFriend
	 */
	private class AsyncDeleteFriend extends AsyncTask<Object, Object, Object>{
		String res = "";
		@Override
		protected Object doInBackground(Object... params) {			
			String response = null;  			
			try {
				response = CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/deleteFriend.php?userID="+userID+ "&friendID="+friendToRemove);
				res=response.toString();
				res = res.trim();
			}catch (Exception e) {} 	
			return null;
		}
		@Override
		protected void onPostExecute(Object result){
			if(res.equals("1")){
				Toast.makeText(getApplicationContext(), "Removed "+ friendToRemove +  " from friendsFromServer list.", Toast.LENGTH_SHORT).show();
				friendsFromServer.remove(newFriend);
				startActivity(new Intent("android.intent.action.FRIENDSACTIVITY"));
			}else{
				Toast.makeText(getApplicationContext(), "Can not remove  "+ friendToRemove +  " from friendsFromServer list. Server respons: " + res, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private void getNewFriendName(){
		final EditText input = new EditText(FriendsActivity.this);
		
		new AlertDialog.Builder(FriendsActivity.this)
	    .setTitle("New Friend")
	    .setMessage("Enter user's name")
	    .setView(input)
	    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	        	newFriend  = input.getText().toString();	
	        	new AsyncAddFriend().execute((Object[]) null);
	        }
	    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            // Do nothing.
	        }
	    }).show();
       
        
	}
}
